//
//  CYHomeProjectViewController.m
//  cyydt
//
//  Created by chu on 2019/1/17.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYHomeChuangYeTongViewController.h"

#import "CYHomeLabelTableViewCell.h"
#import "CYBannerTableViewCell.h"
#import "CYAdvertTableViewCell.h"
#import "CYInformationTableViewCell.h"
#import "CYHeadlineTableViewCell.h"
#import "CYHomePrejectTableViewCell.h"
#import "CYHomeVideoTableViewCell.h"

#import "CYProjectModel.h"
#import "CYProjectDetailViewController.h"
#import "CYHomeVideoDetailsViewController.h"
#import "CYArcitleDetailsViewController.h"

@interface CYHomeChuangYeTongViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>


@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@end

@implementation CYHomeChuangYeTongViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
//    [self.view addSubview:self.tableView];
    [self getData];
    self.tableView.estimatedRowHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CYProjectModel *model = self.dataSourceArr[indexPath.row];
    if ([model.type integerValue] == 28) {
        //视频
        CYHomeVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYHomeVideoTableViewCell"];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CYHomeVideoTableViewCell" owner:nil options:nil][0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    }else if ([model.type integerValue] == 3){
        //广告
        CYAdvertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYAdvertTableViewCell"];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CYAdvertTableViewCell" owner:nil options:nil][0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    }else if ([model.type integerValue] == 10){
        //项目推荐
        CYHomePrejectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYHomePrejectTableViewCell"];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CYHomePrejectTableViewCell" owner:nil options:nil][0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.dataArr = model.list;
        
        return cell;
    }else{
        //资讯
        CYInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYInformationTableViewCell"];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CYInformationTableViewCell" owner:nil options:nil][0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.model = model;
        return cell;
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CYProjectModel *model = self.dataSourceArr[indexPath.row];
    CGFloat height;
    if ([model.type integerValue] == 28) {
        //视频
        height = [[Tool sharedInstance] heightForString:model.title andWidth:kWindowW - 30 fontSize:16];
        
        return height + 85 + 194;
        
    }else if ([model.type integerValue] == 3){
        //广告
        height = [[Tool sharedInstance] heightForString:model.title andWidth:kWindowW - 30 fontSize:16];
        
        return height + 128;
        
    }else if ([model.type integerValue] == 10){
        //项目推荐
        return 280;
        
    }else{
        if ([model.top integerValue] == 1) {
            //置顶
            return 75;
        }else{
            return 116;
        }
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CYProjectModel *model = self.dataSourceArr[indexPath.row];
    if ([model.type integerValue] == 28) {
        //视频
        CYHomeVideoDetailsViewController *detail = [[CYHomeVideoDetailsViewController alloc] init];
        detail.videoId = [model.ID stringValue];
        [[AppDelegate sharedAppDelegate] pushViewController:detail];
    }else if ([model.type integerValue] == 3){
        //广告
        CYProjectDetailViewController *detail = [[CYProjectDetailViewController alloc] init];
        detail.model = model;
        [[AppDelegate sharedAppDelegate] pushViewController:detail];
    }else if ([model.type integerValue] == 10){
        //项目推荐
        
    }else{
        //资讯
        CYArcitleDetailsViewController *detail = [[CYArcitleDetailsViewController alloc] init];
        detail.articleId = [model.ID stringValue];
        [[AppDelegate sharedAppDelegate] pushViewController:detail];
    }
}

- (void)getData{
    self.page = 1;
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"index"];
    NSDictionary *param = @{@"type":@29};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"首页推荐 ---- %@",responseResult);
        [self.tableView removeFromSuperview];
        [self.view addSubview:self.tableView];
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                NSArray *list = data[@"list"];
                [self.dataSourceArr removeAllObjects];
                NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dic in list) {
                    CYProjectModel *model = [CYProjectModel mj_objectWithKeyValues:dic];
                    if ([model.type isEqualToString:@"3"]) {
                        NSString *htmlUrl = [NSString stringWithFormat:@"%@&type=1", [self URLDecodedString:model.mobile_url]];
                        [muArr addObject:htmlUrl];
                    }
                    [self.dataSourceArr addObject:model];
                }
                [self loadHtmlWithCacheWithUrls:muArr];
                [self.tableView reloadData];
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (void)loadHtmlWithCacheWithUrls:(NSArray *)urls{
    
    STMURLCache *sCache = [STMURLCache create:^(STMURLCacheMk *mk) {
        mk.isUsingURLProtocol(NO).cacheTime(20*60*60);
    }];
    [sCache preLoadByWebViewWithUrls:urls];
}

-(NSString *)URLDecodedString:(NSString *)str
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

- (void)getMoreData{
    self.page ++;
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"index"];
    NSDictionary *param = @{@"type":@29, @"page":[NSNumber numberWithInteger:self.page]};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"首页推荐 ---- %@",responseResult);
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
            self.page -- ;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                NSDictionary *data = responseResult[@"data"];
                NSArray *list = data[@"list"];
                NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
                for (NSDictionary *dic in list) {
                    CYProjectModel *model = [CYProjectModel mj_objectWithKeyValues:dic];
                    if ([model.type isEqualToString:@"3"]) {
                        NSString *htmlUrl = [NSString stringWithFormat:@"%@&type=1", [self URLDecodedString:model.mobile_url]];
                        [muArr addObject:htmlUrl];
                    }
                    [self.dataSourceArr addObject:model];
                }
                [self loadHtmlWithCacheWithUrls:muArr];
            }else{
                self.page -- ;
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
        [self.tableView reloadData];

    }];
}

#pragma mark - DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"wuneir"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"当前页面没有内容！";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:RGBOF(0x999999)
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    // 空白页面被点击时开启动画，reloadEmptyDataSet
    [self getData];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, kWindowH - Height_NavBar - Height_TabBar - 44) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = BackGroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self getData];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self getMoreData];
        }];
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        
        [_tableView registerNib:[UINib nibWithNibName:@"CYBannerTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYBannerTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CYInformationTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYInformationTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CYAdvertTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYAdvertTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CYHomeLabelTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYHomeLabelTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CYHeadlineTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYHeadlineTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CYHomePrejectTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYHomePrejectTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CYHomeVideoTableViewCell" bundle:nil] forCellReuseIdentifier:@"CYHomeVideoTableViewCell"];
        
    }
    return _tableView;
}

- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}


@end
